package com.hotel.tv.runtime.security;

import com.autumn.audited.ClientInfoProvider;
import com.autumn.runtime.session.DefaultAutumnUser;
import com.autumn.runtime.session.claims.IdentityClaims;
import com.autumn.security.token.AutumnAuthenticationToken;
import com.autumn.zero.authorization.credential.UserCredentialsService;
import com.hotel.tv.constants.HotelUserRoleConstants;
import com.hotel.tv.constants.HotelUserTypeConstant;
import com.hotel.tv.entities.auth.HotelRole;
import com.hotel.tv.entities.auth.HotelUser;
import com.hotel.tv.runtime.session.HotelAdminSession;
import com.hotel.tv.runtime.session.HotelSession;
import com.hotel.tv.services.HotelAuthorizationService;

/**
 * 用户认证服务
 * <p>
 * </p>
 *
 * @description TODO
 * @author: 老码农
 * @create: 2020-04-02 22:02
 **/
public class HotelUserCredentialsService extends UserCredentialsService<HotelUser, HotelRole> {

    private final boolean adminManager;

    /**
     * @param authorizationService
     * @param clientInfoProvider
     * @param adminManager
     */
    public HotelUserCredentialsService(HotelAuthorizationService authorizationService,
                                       ClientInfoProvider clientInfoProvider, boolean adminManager) {
        super(authorizationService, clientInfoProvider);
        this.adminManager = adminManager;
    }

    @Override
    protected boolean isLoadPermission() {
        return this.adminManager;
    }

    @Override
    protected boolean isLoadClaim() {
        return this.adminManager;
    }


    @Override
    protected DefaultAutumnUser createAutumnUser(HotelUser user, String account,
                                                 String provider,
                                                 String providerKey,
                                                 AutumnAuthenticationToken token) {
        DefaultAutumnUser autumnUser = super.createAutumnUser(user, account, provider, providerKey, token);
        IdentityClaims identityClaims = autumnUser.getIdentityClaims();
        if (this.adminManager) {
            identityClaims.put(HotelSession.FIELD_USER_TYPE, user.getUserType());
            identityClaims.put(HotelAdminSession.FIELD_ORGANIZE_ID, user.getOrganizeId());
            if (user.getUserType().equals(HotelUserTypeConstant.ADMIN)) {
                autumnUser.getRoles().add(HotelUserRoleConstants.ADMINISTRATORS);
            }
            if (user.getUserType().equals(HotelUserTypeConstant.HOTEL_ADMIN)) {
                autumnUser.getRoles().add(HotelUserRoleConstants.HOTEL_USER_ROLE);
            }
        } else {
            identityClaims.put(HotelSession.FIELD_USER_TYPE, HotelUserTypeConstant.USER);
            //是否 vip
        }

        return autumnUser;
    }
}
